import { saveAs } from 'file-saver';

// 格式化日期函数
export const formatDate = (date, format = 'YYYY-MM-DD') => {
  // 处理null或undefined
  if (!date) {
    return '';
  }
  
  // 处理可能的moment.js对象或其他日期包装对象
  let d;
  if (date instanceof Date) {
    d = date;
  } else if (date.toDate) {
    // 处理moment.js对象或其他有toDate方法的对象
    d = date.toDate();
  } else if (typeof date === 'string') {
    d = new Date(date);
  } else {
    // 尝试转换为日期对象
    d = new Date(date);
  }
  
  // 验证是否为有效日期
  if (isNaN(d.getTime())) {
    return '';
  }

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
};

// 校验手机号码格式
export const validatePhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 生成设备信息二维码数据
export const generateQRCodeData = (deviceInfo) => {
  return JSON.stringify(deviceInfo);
};

// 下载图片到本地文件
export const downloadImage = async (imageData, fileName = 'image.png') => {
  try {
    // 创建一个临时的图片对象
    const img = new Image();
    
    return new Promise((resolve, reject) => {
      img.onload = () => {
        // 创建canvas元素
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸与图片一致
        canvas.width = img.width;
        canvas.height = img.height;
        
        // 绘制图片到canvas
        ctx.drawImage(img, 0, 0);
        
        // 转换为blob并下载
        canvas.toBlob((blob) => {
          saveAs(blob, fileName);
          resolve();
        });
      };
      img.onerror = reject;
      img.src = imageData;
    });
  } catch (error) {
    console.error('下载图片失败:', error);
    throw error;
  }
};

// 防抖函数
export const debounce = (func, delay) => {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
};

// 节流函数
export const throttle = (func, limit) => {
  let inThrottle;
  return function (...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

// 深拷贝对象
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item));
  }
  
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
};

// 生成唯一ID
export const generateId = () => {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
};

// 验证Email格式
export const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 隐藏手机号码中间四位
export const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) {
    return phone;
  }
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

// 格式化数字，添加千位分隔符
export const formatNumber = (num) => {
  if (typeof num !== 'number' && typeof num !== 'string') {
    return num;
  }
  
  return Number(num).toLocaleString();
};

// 计算两个日期之间的天数
export const getDateDiff = (startDate, endDate) => {
  const start = typeof startDate === 'string' ? new Date(startDate) : startDate;
  const end = typeof endDate === 'string' ? new Date(endDate) : endDate;
  
  if (!start || !end || isNaN(start.getTime()) || isNaN(end.getTime())) {
    return 0;
  }
  
  const diffTime = Math.abs(end - start);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays;
};

// 检查数组是否包含某个元素
export const arrayIncludes = (arr, item) => {
  return Array.isArray(arr) && arr.indexOf(item) !== -1;
};

// 从数组中移除指定元素
export const removeFromArray = (arr, item) => {
  if (!Array.isArray(arr)) {
    return arr;
  }
  return arr.filter(element => element !== item);
};

// 清空localStorage
export const clearLocalStorage = () => {
  localStorage.clear();
};

// 获取localStorage中的值
export const getFromLocalStorage = (key, defaultValue = null) => {
  try {
    const value = localStorage.getItem(key);
    return value ? JSON.parse(value) : defaultValue;
  } catch (error) {
    console.error('从localStorage读取数据失败:', error);
    return defaultValue;
  }
};

// 保存数据到localStorage
export const saveToLocalStorage = (key, value) => {
  try {
    localStorage.setItem(key, JSON.stringify(value));
    return true;
  } catch (error) {
    console.error('保存数据到localStorage失败:', error);
    return false;
  }
};

// 移除localStorage中的指定键
export const removeFromLocalStorage = (key) => {
  try {
    localStorage.removeItem(key);
    return true;
  } catch (error) {
    console.error('从localStorage删除数据失败:', error);
    return false;
  }
};